package com.wenx.demo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * 1+2+3+4任务分解，每两个数相加然后求和
 */
public class CountTask extends RecursiveTask<Integer> {
    private static final int THREAD_HOLD = 2;

    private int start;
    private int end;

    public CountTask(int start,int end){
        this.start = start;
        this.end = end;
    }
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THREAD_HOLD;
        if(canCompute){
            for(int i = start ;i <= end ;i++){
                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            CountTask left = new CountTask(start,middle);
            CountTask right = new CountTask(middle+1,end);
            //执行子任务
            left.fork();
            right.fork();
            //获取子任务结果
            int lResult = left.join();
            int rResult = right.join();
            sum = lResult + rResult;
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        CountTask task = new CountTask(1,4);
        //submit中提交了一个任务之后，会异步开始执行任务同时返回这个任务，
        // 而 execute会异步执行这个任务但是没有任何返回。
        // 而invoke会异步开始执行任务，直接返回一个结果
//        Future<Integer> result = pool.submit(task);
//        try {
//            System.out.println(result.get());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
        int result = pool.invoke(task);
        System.out.println("result = " + result);

      //  pool.execute(task);
    }
}
